<template>
  <div class="color-picker" @mouseleave="hidePicker">
    <canvas ref="colorWheel" class="color-wheel" @click="pickColor"></canvas>
  </div>
</template>

<script>
export default {
  name: 'ColorPicker',
  data() {
    return {
      selectedColor: 'hsl(0, 100%, 50%)',
    };
  },
  methods: {
    drawColorWheel() {
      const canvas = this.$refs.colorWheel;
      const ctx = canvas.getContext('2d');
      const radius = canvas.width / 2;
      const toRad = (deg) => (deg * Math.PI) / 180;

      for (let angle = 0; angle <= 360; angle += 1) {
        const startAngle = toRad(angle);
        const endAngle = toRad(angle + 1);
        ctx.beginPath();
        ctx.moveTo(radius, radius);
        ctx.arc(radius, radius, radius, startAngle, endAngle);
        ctx.closePath();
        ctx.fillStyle = `hsl(${angle}, 100%, 50%)`;
        ctx.fill();
      }
    },
    pickColor(event) {
      const canvas = this.$refs.colorWheel;
      const ctx = canvas.getContext('2d');
      const rect = canvas.getBoundingClientRect();
      const x = event.clientX - rect.left;
      const y = event.clientY - rect.top;
      const imageData = ctx.getImageData(x, y, 1, 1).data;
      const [r, g, b] = imageData;
      this.selectedColor = `rgb(${r}, ${g}, ${b})`;
      this.$emit('color-picked', this.selectedColor);
    },
    hidePicker() {
      this.$emit('hide-picker');
    }
  },
  mounted() {
    const canvas = this.$refs.colorWheel;
    canvas.width = 300;
    canvas.height = 300;
    this.drawColorWheel();
  }
};
</script>

<style scoped>
.color-picker {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  display: flex;
  flex-direction: column;
  align-items: center;
  z-index: 1000; /* 确保在最上层 */
}

.color-wheel {
  width: 300px;
  height: 300px;
  border-radius: 50%;
  cursor: pointer;
  border: 1px solid #000;
}
</style>
